<template>
	<view class="container">
		<!-- 时间选择器 -->
		<view class="time-selector">
			<text class="time-item" :class="{ active: timeRange === 'today' }" @click="changeTimeRange('today')">今日</text>
			<text class="time-item" :class="{ active: timeRange === 'week' }" @click="changeTimeRange('week')">本周</text>
			<text class="time-item" :class="{ active: timeRange === 'month' }" @click="changeTimeRange('month')">本月</text>
			<text class="time-item" :class="{ active: timeRange === 'custom' }" @click="changeTimeRange('custom')">自定义</text>
		</view>
		
		<!-- 统计卡片 -->
		<view class="stats-cards">
			<view class="stat-card">
				<text class="stat-label">平均pH值</text>
				<text class="stat-value">{{ stats.avgPh }}</text>
				<text class="stat-trend" :class="stats.phTrend > 0 ? 'up' : 'down'">
					{{ stats.phTrend > 0 ? '↗' : '↘' }} {{ Math.abs(stats.phTrend) }}%
				</text>
			</view>
			<view class="stat-card">
				<text class="stat-label">平均温度</text>
				<text class="stat-value">{{ stats.avgTemp }}°C</text>
				<text class="stat-trend" :class="stats.tempTrend > 0 ? 'up' : 'down'">
					{{ stats.tempTrend > 0 ? '↗' : '↘' }} {{ Math.abs(stats.tempTrend) }}%
				</text>
			</view>
			<view class="stat-card">
				<text class="stat-label">平均浊度</text>
				<text class="stat-value">{{ stats.avgTurbidity }}NTU</text>
				<text class="stat-trend" :class="stats.turbidityTrend > 0 ? 'up' : 'down'">
					{{ stats.turbidityTrend > 0 ? '↗' : '↘' }} {{ Math.abs(stats.turbidityTrend) }}%
				</text>
			</view>
			<view class="stat-card">
                
			</view>
		</view>
		
		<!-- 图表区域 -->
		<view class="chart-section">
			<view class="chart-header">
				<text class="chart-title">数据趋势图</text>
				<view class="chart-controls">
					<text class="time-range">{{ getTimeRangeText() }}</text>
					<uni-icons type="calendar" size="20" color="#666"></uni-icons>
				</view>
			</view>
			<view class="chart-container">
				<qiun-data-charts 
					:type="chartType"
					:opts="chartOpts"
					:chartData="chartData"
					:canvasId="'analysisChart'"
					:canvas2d="true"
				/>
			</view>
		</view>
		
		<!-- 数据表格 -->
		<view class="table-section">
			<view class="table-header">
				<text class="table-title">详细数据</text>
				<view class="filter-controls">
					<uni-data-select
						v-model="timeRange"
						:localdata="timeRangeOptions"
						@change="handleTimeRangeChange"
						class="time-select"
					></uni-data-select>
					<uni-data-select
						v-model="chartType"
						:localdata="chartTypeOptions"
						@change="handleChartTypeChange"
						class="chart-select"
					></uni-data-select>
				</view>
			</view>
			<scroll-view scroll-y class="data-table">
				<view class="table-row header">
					<text class="table-cell">时间</text>
					<text class="table-cell">pH值</text>
					<text class="table-cell">温度(°C)</text>
					<text class="table-cell">浊度(NTU)</text>
                    
					<text class="table-cell">水质等级</text>
				</view>
				<view class="table-row" v-for="(item, index) in historicalData" :key="index">
					<text class="table-cell">{{ formatTime(item.time) }}</text>
					<text class="table-cell">{{ item.phValue }}</text>
					<text class="table-cell">{{ item.temperature }}</text>
					<text class="table-cell">{{ item.turbidity }}</text>
                    
					<text class="table-cell" :class="getQualityClass(item.quality)">{{ item.quality }}</text>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'

// 响应式数据
const timeRange = ref('today')
const chartType = ref('line')

const stats = ref({
	avgPh: 7.1,
	phTrend: 1.2,
	avgTemp: 23.1,
	tempTrend: -0.5,
	avgTurbidity: 2.3,
	turbidityTrend: 0.8,
	avgOxygen: 7.9,
	oxygenTrend: 1.5
})

const historicalData = ref([
	{ time: '2025/09/22 08:00', phValue: 7.2, temperature: 22.5, turbidity: 1.8, quality: '优秀' },
	{ time: '2025/09/22 09:00', phValue: 7.1, temperature: 22.8, turbidity: 2.0, quality: '优秀' },
	{ time: '2025/09/22 10:00', phValue: 7.3, temperature: 23.0, turbidity: 1.9, quality: '优秀' },
	{ time: '2025/09/22 11:00', phValue: 6.8, temperature: 23.5, turbidity: 3.1, quality: '良好' },
	{ time: '2025/09/22 12:00', phValue: 7.0, temperature: 23.2, turbidity: 2.5, quality: '优秀' }
])

const timeRangeOptions = ref([
	{ value: 'today', text: '今日' },
	{ value: 'week', text: '本周' },
	{ value: 'month', text: '本月' },
	{ value: 'custom', text: '自定义' }
])

const chartTypeOptions = ref([
	{ value: 'line', text: '折线图' },
	{ value: 'bar', text: '柱状图' }
])

// uCharts配置
const chartOpts = ref({
	color: ['#3498db', '#e74c3c', '#9b59b6', '#27ae60'],
	padding: [15, 15, 0, 15],
	enableScroll: true,
	legend: {
		show: true,
		position: 'bottom',
		lineHeight: 25
	},
	xAxis: {
		disableGrid: false,
		itemCount: 12,
		scrollShow: true
	},
	yAxis: {
		gridType: 'dash',
		dashLength: 2,
		splitNumber: 5
	},
	extra: {
		line: {
			type: 'curve',
			width: 3,
			activeType: 'hollow'
		},
		bar: {
			categoryGap: 0.3
		}
	}
})

const chartData = ref({
	categories: ['00:00', '02:00', '04:00', '06:00', '08:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00'],
	series: [
		{
			name: 'pH值',
			data: [7.2, 7.1, 7.3, 7.0, 7.4, 7.2, 7.1, 7.3, 7.0, 7.4, 7.2, 7.1]
		},
		{
			name: '温度',
			data: [22.5, 22.3, 22.7, 22.1, 22.9, 22.6, 22.4, 22.8, 22.2, 22.7, 22.5, 22.3]
		},
		{
			name: '浊度',
			data: [1.8, 1.9, 1.7, 2.0, 1.6, 1.8, 1.9, 1.7, 2.1, 1.5, 1.8, 1.9]
        }
	]
})

// 页面加载
onMounted(() => {
	loadAnalysisData()
})

// 加载分析数据
const loadAnalysisData = () => {
	console.log('加载分析数据...')
	// 实际项目中会从后端API获取数据
}

// 处理时间范围变化
const handleTimeRangeChange = (value) => {
	console.log('时间范围变化:', value)
	updateChartData()
}

// 处理图表类型变化
const handleChartTypeChange = (value) => {
	console.log('图表类型变化:', value)
	chartType.value = value
}

// 更新图表数据
const updateChartData = () => {
	// 根据时间范围生成不同的数据
	let newData = {
		categories: chartData.value.categories,
		series: chartData.value.series
	}
	
	if (timeRange.value === 'week') {
		// 周数据
		newData.categories = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
		newData.series = [
			{
				name: 'pH值',
				data: generateRandomData(7, 6.5, 8.5)
			},
			{
				name: '温度',
				data: generateRandomData(7, 20, 25)
			},
			{
				name: '浊度',
				data: generateRandomData(7, 1, 4)
            }
		]
	} else if (timeRange.value === 'month') {
		// 月数据
		newData.categories = ['第1周', '第2周', '第3周', '第4周']
		newData.series = [
			{
				name: 'pH值',
				data: generateRandomData(4, 6.5, 8.5)
			},
			{
				name: '温度',
				data: generateRandomData(4, 20, 25)
			},
			{
				name: '浊度',
				data: generateRandomData(4, 1, 4)
            }
		]
	}
	
	chartData.value = newData
}

// 生成随机数据
const generateRandomData = (count, min, max) => {
	const data = []
	for (let i = 0; i < count; i++) {
		data.push(Math.round((min + Math.random() * (max - min)) * 10) / 10)
	}
	return data
}

// 获取水质等级样式类
const getQualityClass = (quality) => {
	const classMap = {
		'优秀': 'excellent',
		'良好': 'good',
		'一般': 'average',
		'较差': 'poor'
	}
	return classMap[quality] || ''
}

// 获取时间范围文本
const getTimeRangeText = () => {
	const rangeMap = {
		today: '今日',
		week: '本周',
		month: '本月',
		custom: '自定义'
	}
	return rangeMap[timeRange.value] || '今日'
}

// 格式化时间
const formatTime = (time) => {
	const date = new Date(time)
	const hours = date.getHours().toString().padStart(2, '0')
	const minutes = date.getMinutes().toString().padStart(2, '0')
	return `${hours}:${minutes}`
}

// 时间范围切换
const changeTimeRange = (range) => {
	timeRange.value = range
	drawChart()
}
</script>

<style lang="scss" scoped>
.container {
	padding: 20rpx;
	background: #f5f7fa;
	min-height: 100vh;
}

.time-selector {
	display: flex;
	background: #ffffff;
	border-radius: 12rpx;
	padding: 10rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.time-item {
	flex: 1;
	text-align: center;
	padding: 20rpx;
	border-radius: 12rpx;
	font-size: 24rpx;
	color: #7f8c8d;
	transition: all 0.3s;
	font-weight: 500;
	
	&.active {
		background: #3498db;
		color: #ffffff;
		box-shadow: 0 2rpx 10rpx rgba(52, 152, 219, 0.3);
	}
}

.stats-cards {
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 20rpx;
	margin-bottom: 30rpx;
}

.stat-card {
	background: #ffffff;
	border-radius: 12rpx;
	padding: 30rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
	transition: all 0.3s;
	
	&:active {
		transform: scale(0.98);
		box-shadow: 0 1rpx 6rpx rgba(0, 0, 0, 0.12);
	}
}

.stat-label {
	font-size: 22rpx;
	color: #7f8c8d;
	margin-bottom: 10rpx;
	display: block;
}

.stat-value {
	font-size: 32rpx;
	font-weight: bold;
	color: #2c3e50;
	margin-bottom: 10rpx;
	display: block;
}

.stat-trend {
	font-size: 20rpx;
	font-weight: bold;
	
	&.up {
		color: #27ae60;
	}
	
	&.down {
		color: #e74c3c;
	}
}

.chart-section {
	background: #ffffff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.chart-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.chart-title {
	font-size: 28rpx;
	font-weight: bold;
	color: #2c3e50;
}

.chart-controls {
	display: flex;
	align-items: center;
	gap: 10rpx;
}

.time-range {
	font-size: 22rpx;
	color: #7f8c8d;
}

.chart-container {
	height: 500rpx;
	background: #f8f9fa;
	border-radius: 8rpx;
	overflow: hidden;
}

.chart-canvas {
	width: 100%;
	height: 100%;
}

.table-section {
	background: #ffffff;
	border-radius: 12rpx;
	padding: 30rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.table-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.table-title {
	font-size: 28rpx;
	font-weight: bold;
	color: #2c3e50;
}

.filter-controls {
	display: flex;
	gap: 15rpx;
}

.time-select, .chart-select {
	width: 120rpx;
}

.data-table {
	max-height: 600rpx;
}

.table-row {
	display: flex;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #ecf0f1;
	
	&.header {
		font-weight: bold;
		background: #f8f9fa;
		margin: 0 -30rpx;
		padding: 20rpx 30rpx;
	}
	
	&:last-child {
		border-bottom: none;
	}
}

.table-cell {
	flex: 1;
	font-size: 22rpx;
	color: #2c3e50;
	text-align: center;
	
	&.excellent {
		color: #27ae60;
		font-weight: bold;
	}
	
	&.good {
		color: #f39c12;
		font-weight: bold;
	}
	
	&.average {
		color: #e67e22;
		font-weight: bold;
	}
	
	&.poor {
		color: #e74c3c;
		font-weight: bold;
	}
}
</style>